import json
import random
import string
from datetime import datetime
import config
from exts import db,mail
from flask import Flask,request,jsonify,Blueprint,session
from flask_mail import Message
bp = Blueprint("user",__name__,url_prefix='/user')
34566
@bp.route("/register",methods=['GET','POST'])
def regiter():
    engine = db.get_engine()
    data = request.data
    user_info = json.loads(data)
    acountname = user_info.get('acountName')
    nicktname = user_info.get('nicktName')
    phone = user_info.get('phone')
    email = user_info.get('email')
    password = user_info.get('password')
    captcha = user_info.get('captcha')
    print(email)
    if user_info.get('type') == 'getCaptcha':
        letters = string.digits
        captcha = "".join(random.sample(letters,6))
        if email:
            print("77777")
            message = Message(subject='您的BBS邮箱验证码',
                              recipients=[email],
                              body=f"【BBS】您注册BBS论坛的验证码是：{captcha},请勿泄露您的验证码，若非本人操作，请忽略该邮件。"
                              )
            mail.send(message)
            return {'captcha':captcha}
    else:
        with engine.connect() as conn:
            try:
                conn.execute(f"insert into user (acountname, nickname, email, phone, password,registertime)values ('{acountname}','{nicktname}','{phone}','{email}','{password}','{datetime.now()}');")
            except:
                return {'status':'userExists'}
    return 'ok'

@bp.route("/log",methods=['GET','POST'])
def log():
    engine = db.get_engine()
    data = request.data
    user_info = json.loads(data)
    acountname = user_info.get('acountname')
    password = user_info.get('password')
    user_id = user_info.get('id')
    with engine.connect() as conn:
        res = conn.execute(f"select * from user where acountname = '{acountname}'")
        item = res.fetchone()
        if res != None:
            if item[5] == password:
                return {'status':'ok','nickname':item[2]}
            else :
                return {'status':'nook'}
        else:
            return {'status':'nook'}

@bp.route("/modify",methods=['GET','POST'])
def modify():
    engine = db.get_engine()
    print(request.data,'   111111111111111111!',type(request.data))
    userinfo = json.loads(request.data)
    if userinfo.get('type') == 'get':
        nickname = userinfo.get('nickname')
        print(nickname)
        with engine.connect() as conn:
            item = conn.execute(f"select acountname,nickname,phone,email,password from user where nickname = '{nickname}'")
            user = item.fetchone()
            print(user)
            newuser = {'acountname':user[0], 'nickname':user[1], 'phone':user[2], 'email':user[3], 'password':user[4]}
            return {'newuser':newuser}
    else:
        olduser = userinfo.get('useInfo')
        print(olduser)
        with engine.connect() as conn:
            try:
                item = conn.execute(f"update user set nickname = '{olduser.get('nickname')}',phone = '{olduser.get('phone')}',email = '{olduser.get('email')}', password = '{olduser.get('password')}' where acountname = '{olduser.get('acountname')}'")
                return {'status': 'ok'}
            except:
                return {'status':'userExists'}


@bp.route("/personpage",methods=['GET','POST'])
def person():
    pass

@bp.route('/userAllInfo',methods=['POST','GET'])
def getAllInfo():
    data=json.loads(request.data)
    nickName=data.get('nickname')
    engine = db.get_engine()
    item = None
    with engine.connect() as conn:
        cursor = conn.execute(f"select acountname,nickname,articlenum,carenum from user where nickname='{nickName}' ")
        item = cursor.fetchone()
        userinfo = {
            'acountname': item[0],
            'nickname': item[1],
            'articlenum': item[2],
            'carenum': item[3]
        }
        return {'userinfo': userinfo}

# 前端 CareAbout 页面通过账号请求关注信息
@bp.route('/mycare',methods=['GET','POST'])
def myCare():
    # 获取账号名
    engine = db.get_engine()
    data = json.loads(request.data)
    acountname = data.get('acountname')
    print(acountname)
    # 数据库查找关注的账号
    with engine.connect() as conn:
        res = conn.execute(f"select care,becare from careandbecare where care='{acountname}'")
        # 存放对应昵称用户
        careUser = []
        itemList = res.fetchall()
        for item in itemList:
            print(item)
            nickname = conn.execute(f"select nickname from user where acountname='{item[1]}'")
            careUser.append(nickname.fetchone()[0])
        print(careUser)
    return {'careUser':careUser}

# 前端 CareAbout 页面通过账号请求关注信息
@bp.route('/careme',methods=['GET','POST'])
def careMe():
    # 获取账号名
    engine = db.get_engine()
    data = json.loads(request.data)
    acountname = data.get('acountname')
    print(acountname)
    # 数据库查找关注的账号
    with engine.connect() as conn:
        res = conn.execute(f"select care,becare from careandbecare where becare='{acountname}'")
        # 存放对应昵称用户
        careUser = []
        itemList = res.fetchall()
        for item in itemList:
            print(item)
            nickname = conn.execute(f"select nickname from user where acountname='{item[0]}'")
            careUser.append(nickname.fetchone()[0])
        print(careUser)
    return {'careUser':careUser}

# 前端 Article 页面根据账号查找文章
@bp.route('/myarticle',methods=['GET','POST'])
def getArticle():
    # 获取账号名
    engine = db.get_engine()
    data=json.loads(request.data)
    acountname=data.get('acountname')
    # 数据库查找
    with engine.connect() as conn:
        sql= f"select title,content,agreenum,posttime from article where user_account='{ acountname }'"
        res = conn.execute(sql)
    # 存放文章
        article=[]
        for item in res.fetchall():
            print(item)
            art={
                'title':item[0],
                'content':item[1],
                'agreenum':item[2],
                'posttime':item[3]
            }
        # 添加每一篇文章
            article.append(art)
    # 将文章返回给前端
    return {'article':article}